package com.cea.papyrus.diagram.classdiagram.editpart;

import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.DragTracker;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.palette.PaletteDrawer;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.Dependency;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.ElementImport;
import org.eclipse.uml2.uml.Generalization;
import org.eclipse.uml2.uml.TemplateSignature;

import com.cea.papyrus.core.PapyrusMessages;
import com.cea.papyrus.core.PapyrusPlugin;
import com.cea.papyrus.core.editor.ModelManager;
import com.cea.papyrus.core.editor.mouseoveraction.ActionHandleManager;
import com.cea.papyrus.core.editpart.ContainerWithSemanticEditPart;
import com.cea.papyrus.core.figures.IconFigure;
import com.cea.papyrus.core.figures.TemplateSignatureFigure;
import com.cea.papyrus.core.ui.dialogs.PapyrusMessageDialog;
import com.cea.papyrus.core.utils.Debug;
import com.cea.papyrus.diagram.classdiagram.helper.NodeTemplateSignatureHelper;
import com.cea.papyrus.diagraminterchange2.di2.GraphNode;
import com.cea.papyrus.diagraminterchange2.di2.Uml1SemanticModelBridge;

/**
 * Controller class for {@link TemplateSignature}.
 */
public class TemplateSignatureEditPart extends ContainerWithSemanticEditPart {

	/**
	 * Creates a new TemplateSignatureEditPart.
	 * @param modelManager manager in charge of models, graphic and domain
	 * @param graphNode parent of the graph node controlled by this edit part
	 */
	public TemplateSignatureEditPart(GraphNode graphNode,ModelManager modelManager) {
		super(graphNode,modelManager);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void createEditPolicies(){
		super.createEditPolicies();
		installEditPolicy(DimensionAdaptationClassEditPolicy.DIMENSION_ADAPTATION, new DimensionAdaptationClassEditPolicy());
		if(! this.isElementImport()){
			installActionHandle();
		}
	}

	/**
	 * Install Action handles for this editPart.
	 * Use same toolEntries than in palette
	 */
	protected void installActionHandle() {
		// Install mouse hover
		ActionHandleManager actionMngr = new ActionHandleManager(this);	
		// Create a toolbar of actions.
		PaletteDrawer entries = new PaletteDrawer("creation tool");
		try{
			entries.add(PapyrusPlugin.creationToolFactory.getConnectionCreationToolEntry(
					PapyrusMessages.AddAssociationCommand_Label, 
					PapyrusMessages.AddAssociationCommand_Description, 
					Association.class, 
					null));
			entries.add(PapyrusPlugin.creationToolFactory.getConnectionCreationToolEntry(
					PapyrusMessages.AddGeneralizationCommand_Label,
					PapyrusMessages.AddGeneralizationCommand_Description,
					Generalization.class,
					null));
			entries.add(PapyrusPlugin.creationToolFactory.getConnectionCreationToolEntry(
					PapyrusMessages.AddDependencyCommand_Label,
					PapyrusMessages.AddDependencyCommand_Description,
					Dependency.class,
					null));
			entries.add(PapyrusPlugin.creationToolFactory.getConnectionCreationToolEntry(
					PapyrusMessages.AddTemplateSignatureCommand_Label,
					PapyrusMessages.AddTemplateSignatureCommand_Description,
					TemplateSignature.class,
					null));
		}
		catch (Exception e) {
			PapyrusMessageDialog.display(e.getMessage(), e);
		}
		actionMngr.addTool(entries, PositionConstants.EAST, false, 5);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected IFigure createFigure() {
		// Try to get figure from ContainerWithSemanticEditPart
		IFigure fig = super.createFigure();
		if (fig != null) {
			return fig;
		}
		// else
		return new TemplateSignatureFigure();				
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public IFigure getContentPane() {
		if (getFigure() instanceof TemplateSignatureFigure) {
			return ((TemplateSignatureFigure) getFigure()).getContentPane();
		} else {
			// Figure is a shape
			return getFigure();
		}
	}

	/**
	 * Create the child <code>EditPart</code>
	 * for the given model object. This method is called from {@link #refreshChildren()}.
	 * <p>
	 * It adds the different container for template paramaters and other lists. 
	 * </p>
	 * @param model the Child model object
	 * @return The child EditPart
	 */
	@Override
	protected EditPart createChild(Object model) {
		if( model instanceof GraphNode) {
			EditPart part = null;
			if( ! this.isElementImport()){
				//first graph Node= container of attributes
				if( ((GraphNode)model) == ((GraphNode)getGraphNode().getContained().get(0)) ) {
					part = new TemplateParameterListEditPart((GraphNode)model,modelManager);
				} else {
					throw new RuntimeException("unknown model list");
				}

				part.setModel(model);
				return part;
			}
		}
		return super.createChild(model);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public TemplateSignature getUmlElement() {
		Element e=((Uml1SemanticModelBridge)getGraphNode().getSemanticModel()).getElement();
		// case of element import
		if(e instanceof ElementImport){
			return (TemplateSignature)((ElementImport) e).getImportedElement();
		}
		// this is a simple Class
		return (TemplateSignature)e;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void refreshVisuals() {
		Debug.debug(this, "refreshvisuals", 30);

		Dimension size = getGraphNode().getSize();
		Point p = getGraphNode().getPosition();
		Rectangle r = new Rectangle(p ,size);
		IFigure fig = getFigure();

		// if fig is a stereotype figure
		if (fig instanceof TemplateSignatureFigure) {
			// Retrieve current class and figure
			org.eclipse.uml2.uml.TemplateSignature currentTemplateSignature = (org.eclipse.uml2.uml.TemplateSignature) getUmlElement();
			// if fig is a ClassFigure
			//((NodeFigure) fig).refreshColors(getGraphNode());
			//((NodeFigure) fig).refreshPresentation(getPresentation(), currentTemplateSignature, getGraphNode());
			fig.setBackgroundColor(ColorConstants.white);
		}
		((GraphicalEditPart) getParent()).setLayoutConstraint(this, fig, r);
	}

	/**
	 * Returns the Name Label of this edit part.
	 * @return Label the label figure from the graphical representation
	 */
	protected Label getNameLabel() {
		IFigure fig = getFigure();
		if (fig instanceof IconFigure) {
			return (Label) fig;
		} else if (fig instanceof TemplateSignatureFigure) {
			return ((TemplateSignatureFigure) fig).getNameLabel();
		} else {
			Debug.error(this, "TemplateSignatureEditPart::getTextFigure() : Unknown Figure type.", channel);
			return null;
		}
	}

//	/**
//	 * Init the label direct edit manager.
//	 * This method should be called when a Direct Edit request is performed.
//	 */
//	protected void initLabelEditManager() {
//		if(manager==null) {
//			// locator for the cell editor (on the name label)
//			CellEditorLocator locator = new LabelCellEditorLocator(getNameLabel());
//
//			// defining how properties are modified in the model
//			PropertyAccessor accessor = new PropertyAccessor() {
//				public String getPropertyName() {
//					return "Name";
//				}
//
//				public String getValue() {
//					if(isElementImport()){
//						return getElementImport().getAlias();
//					}
////					return getUmlElement().getName();
//					return "template signature" ;
//				}
//				public void setValue(String value) {
//					if(isElementImport()){
//						getElementImport().setAlias(value);
//					}
//					//else{getUmlElement().setName(value);}  
//				}
//			};
//			// defines the controler: link between model and view
//			ILabelControler labelControler = new LabelControler(getNameLabel(), accessor);
//
//			// creates the editing manager.
//			manager = new LabelDirectEditManager(this, locator, labelControler);
//		}
//	}
//
//
//	/**
//	 * the direct edit mechanism requires the edit part to handle the direct edit
//	 * request.
//	 * @param req the request that called the direct edit.
//	 */
//	public void performDirectEdit(Request req) {
//		initLabelEditManager();
//		manager.show();
//	}
//
//	/* (non-Javadoc)
//	 * @see org.eclipse.gef.editparts.AbstractEditPart#performRequest(org.eclipse.gef.Request)
//	 */
//	@Override
//	public void performRequest(Request request){
//		if (RequestConstants.REQ_DIRECT_EDIT.equals(request.getType())) {
//			performDirectEdit(request);
//		}
//	}

	/**
	 * this method calculate the good position of the signature by taking account of his parent.
	 * @param point the position of the current port ins absolute coordinate
	 * @return the new position of the port.
	 */
	public Point inRunnerOfClass(Point point){
		Dimension templateSignatureNodeDimension = getGraphNode().getSize();
		//apply good position , the defaut is the same point
		NodeTemplateSignatureHelper np= new NodeTemplateSignatureHelper();
		return np.inRunner((GraphNode)getGraphNode().getSemanticParent(), point, templateSignatureNodeDimension);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public DragTracker getDragTracker(Request request) {
		return new TemplateSignatureTracker(this);
	}
}
